package middleware

import (
	"api/internal/types"
	jwt "github.com/golangblogs/gojwt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"strconv"
	"sus/appconfig"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation

		// Passthrough to next handler if need
		token := r.Header.Get("token")
		if token == "" {
			resp := types.Response{
				Message: "token is null",
				Code:    10001,
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		newJWT := jwt.NewJWT(appconfig.AppConf.Jwt.APP_KEY)
		clamis, err := newJWT.ParseToken(token)
		if err != nil {
			resp := types.Response{
				Message: "token is invalid",
				Code:    10002,
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
		r.ParseForm()
		r.Form.Set("userId", strconv.Itoa(int(clamis.ID)))
		next(w, r)
	}
}
